﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Utilities
{
    public class JObjectHelper
    {
        public static IDictionary<string, object> JObject2Dic(JObject data)
        {
            IDictionary<string, JToken> dataDic = (JObject)data;
            Dictionary<string, object> res = dataDic.ToDictionary(pair => pair.Key, pair => (object)pair.Value.ToObject<object>());
            return res;
        }
        public static IDictionary<string, object> Object2Dic(object data)
        {
            Dictionary<string, object> res = new Dictionary<string, object>();
            var ParentType = data.GetType();
            if (ParentType.Name == "DapperRow") return (IDictionary<string, object>)data;
            var Properties = ParentType.GetProperties();
            foreach (var Propertie in Properties)
            {
                //循环遍历属性
                if (Propertie.CanRead && Propertie.CanWrite)
                {
                    object val = Propertie.GetValue(data, null);
                    if (Propertie.PropertyType.IsEnum) val = (int)val;
                    res.Add(Propertie.Name, val);
                }
            }
            return res;
        }
        public static IDictionary<string, dynamic> Object2Dic1(dynamic data)
        {
            Dictionary<string, dynamic> res = new Dictionary<string, dynamic>();
            //var ParentType = data.GetType();
            //if (ParentType == "DapperRow") return (IDictionary<string, dynamic>)data;
            //var Properties = ParentType.GetProperties();
            //foreach (var Propertie in Properties)
            //{
            //    //循环遍历属性
            //    if (Propertie.CanRead && Propertie.CanWrite)
            //    {
            //        object val = Propertie.GetValue(data, null);
            //        if (Propertie.PropertyType.IsEnum) val = (int)val;
            //        res.Add(Propertie.Name, val);
            //    }
            //}
            return res;
        }
    }
}
